import { ref } from 'vue'
import request from '@/utils/request'
import { defineStore } from 'pinia'
import { commodityListService } from '@/api/commodity'
import { debounce } from 'lodash'

// 商品分类函数
export const useCommodityStore = defineStore('commodity', () => {
    // 搜索关键字
    const searchText = ref('')
    // 商品列表
    const overview = ref([])
    // 加载状态
    const loading = ref(false)
    // 页码
    const pageNum = ref(1)
    // 分类
    const categoryId = ref(0)

    // 清空
    const clearList = () => {
        overview.value = []
        loading.value = false
        pageNum.value = 1
        searchText.value = null
        categoryId.value = 0
    }

    // 获取商品列表，可以根据分类和搜索关键字获取
    const getOverview =  debounce(async() => {
        let res = await commodityListService(pageNum.value, searchText.value, categoryId.value);
        if(res.data == null){
            loading.value = true;
            return;
        }
        // 遍历res添加进overview
        for (let i = 0; i < res.data.length; i++) {
            overview.value.push(res.data[i]);
        }
        // pageNum自增
        pageNum.value = pageNum.value + 1;
    }, 300);

    return {
        searchText,
        overview,
        loading,
        pageNum,
        categoryId,
        getOverview,
        clearList
    }
}, {
    persist: true,
})